import { createRouter, createWebHistory } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'

const routes: RouteRecordRaw[] = [
  {
    path: '/',
    name: 'layout',
    component: () => import('../layout/BasicLayout.vue'),
    redirect: '/exam',
    children: [
      {
        path: '/login',
        name: 'Login',
        component: () => import('../views/login/Login.vue'),
        meta: {
          title: '登录'
        }
      },
      {
        path: 'exam',
        name: 'exam',
        component: () => import('../views/exam/ExamList.vue')
      },
      {
        path: 'exam/:id',
        name: 'examDetail',
        component: () => import('../views/exam/ExamDetail.vue')
      },
      {
        path: 'score',
        name: 'ScoreList',
        component: () => import('../views/score/ScoreList.vue')
      },
      {
        path: 'exam/:id/take',
        name: 'examTake',
        component: () => import('../views/exam/ExamTake.vue')
      }
    ]
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 全局路由守卫
router.beforeEach((to, from, next) => {
  const token = localStorage.getItem('token')
  const publicPages = ['/login'] // 无需登录即可访问的页面
  const authRequired = !publicPages.includes(to.path)
  
  // 设置页面标题
  document.title = (to.meta.title as string) || '在线考试系统'
  
  if (authRequired && !token) {
    // 需要认证但未登录，重定向到登录页
    next({
      path: '/login',
      query: { redirect: to.fullPath }
    })
  } else if (to.path === '/login' && token) {
    // 已登录用户访问登录页，重定向到首页
    next('/exam')
  } else {
    // 其他情况正常访问
    next()
  }
})

export default router